package com.dicsystems.myrec;

import com.dicsystems.myrec.dto.Category;
import com.dicsystems.myrec.dto.Holiday;
import com.dicsystems.myrec.dto.Image;
import com.dicsystems.myrec.dto.Todo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	private Common co = new Common();

	public DatabaseHelper(Context context) {
		super(context, "myrec", null, 1);
		co.me = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();
		db.execSQL(co.read("sql/table_holiday.sql"));
		db.execSQL(co.read("sql/table_category.sql"));
		db.execSQL(co.read("sql/table_todo.sql"));
		db.execSQL(co.read("sql/table_image.sql"));
		db.execSQL(co.read("sql/index_category_id.sql"));
		db.execSQL(co.read("sql/index_start_date.sql"));
		db.execSQL(co.read("sql/index_end_date.sql"));
		db.execSQL(co.read("sql/index_todo_id.sql"));
		addHoliday(db);
		addCategory(db);
		addTodo(db);	//test
		addImage(db);	//test
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

	private void addHoliday(SQLiteDatabase db) {
		String[] array = co.read("data/holiday.csv").split("\n");
		for(int i = 0; i < array.length; i++) {
			db.insert("holiday", null, new Holiday(array[i].split(",")).get());
		}
	}

	private void addCategory(SQLiteDatabase db) {
		String[] array = co.read("data/category.csv").split("\n");
		for(int i = 0; i < array.length; i++) {
			db.insert("category", null, new Category(array[i].split(",")).get());
		}
	}

	private void addTodo(SQLiteDatabase db) {
		String[] array = co.read("data/todo.csv").split("\n");
		for(int i = 0; i < array.length; i++) {
			db.insert("todo", null, new Todo(array[i].split(",")).get());
		}
	}

	private void addImage(SQLiteDatabase db) {
		String[] array = co.read("data/image.csv").split("\n");
		for(int i = 0; i < array.length; i++) {
			db.insert("image", null, new Image(array[i].split(",")).get());
		}
	}
}
